import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../model/community_video_model.dart';

import '../common/routes.dart';
import '../model/video_item_model.dart';

class FocusListView extends StatefulWidget {
  const FocusListView({super.key});

  @override
  State<FocusListView> createState() => _FocusListViewState();
}

class _FocusListViewState extends State<FocusListView> with AutomaticKeepAliveClientMixin {
  final ScrollController _scrollController = ScrollController();
  final List<IssueList> _videoList = [];
  bool _isLoadingData = true;
  bool _isLoadingMore = false;
  bool _hasMore = true;
  var _url = "https://baobab.kaiyanapp.com/api/v4/tabs/follow";

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent && !_isLoadingMore) {
        _loadMore();
      }
    });

    loadData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  _loadMore() async {
    setState(() {
      _isLoadingMore = true;
    });
    await loadData();
  }

  loadData() async {
    Dio dio = Dio();
    final response = await dio.get(_url);
    var model = CommunityVideoModel.fromJson(response.data);
    var count = model.count ?? 0;
    setState(() {
      _isLoadingData = false;
      _isLoadingMore = false;
      if (count > 0) {
        _url = model.nextPageUrl ?? '';
        _videoList.addAll(model.itemList ?? []);
      } else {
        _hasMore = false;
      }
    });
  }

  _buildItem(VideoItemModel item) {
    double screenWidth = Get.width;
    return GestureDetector(
      child: Container(
        margin: EdgeInsets.only(right: 10),
        width: screenWidth - 40,
        height: 200,
        child: Stack(
          children: [
            CachedNetworkImage(
              width: double.infinity,
              height: 200,
              fadeInDuration: const Duration(seconds: 0),
              fadeOutDuration: const Duration(seconds: 0),
              fit: BoxFit.cover,
              imageUrl: item.data.cover?.feed ?? '',
              placeholder: (context, url) {
                return Image.asset(
                  "assets/images/placeholder.png",
                  fit: BoxFit.cover,
                );
              },
            ),
            Positioned(
              left: 0,
              top: 0,
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.red,
                  borderRadius: BorderRadius.only(
                    bottomRight: Radius.circular(16),
                  ),
                ),
                width: 46,
                height: 22,
                child: Padding(
                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 1),
                  child: Text(
                    item.data.category ?? '',
                    style: TextStyle(color: Colors.white, fontSize: 13),
                  ),
                ),
              ),
            )
          ],
        ),
      ),
      onTap: () {
        Get.toNamed(Routes.VIDEO_DETAIL, arguments: {"id": item.data.id, "playUrl": item.data.playUrl});
      },
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);

    if (_isLoadingData) {
      return Center(
        child: Container(
          margin: const EdgeInsets.all(8.0),
          width: 64.0,
          height: 64.0,
          child: const CircularProgressIndicator(),
        ),
      );
    }
    return ListView.builder(
      controller: _scrollController,
      itemCount: _videoList.length + 1,
      itemBuilder: (context, index) {
        if (index == _videoList.length) {
          if (_isLoadingMore) {
            // Show loading indicator
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: CircularProgressIndicator()),
            );
          } else if (!_hasMore) {
            // No more data
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: Text('没有更多数据了')),
            );
          } else {
            return SizedBox.shrink();
          }
        }

        final item = _videoList[index];
        return Container(
          color: Colors.white,
          margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
          child: Column(
            children: [
              Row(
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(20),
                    child: CachedNetworkImage(
                      fit: BoxFit.cover,
                      fadeInDuration: const Duration(milliseconds: 100),
                      fadeOutDuration: const Duration(seconds: 0),
                      imageUrl: item.data?.header?.icon ?? '',
                      width: 40,
                      height: 40,
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item.data?.header?.title ?? '',
                            style: TextStyle(fontSize: 18),
                          ),
                          Text(
                            item.data?.header?.description ?? '',
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: 14,
                              color: Colors.black.withOpacity(.5),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
              Container(
                color: Colors.white,
                height: 200,
                width: double.infinity,
                child: ListView.builder(
                  itemCount: _videoList[index].data?.itemList?.length,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (c, i) {
                    var item = _videoList[index].data?.itemList?[i];
                    return _buildItem(item!);
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
